#include <ctype.h>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>

using std::cout;
using std::endl;
using std::cerr;
using std::string;
using std::vector;
using std::ifstream;
using std::ofstream;
using std::istringstream;

struct Record
{
    Record(const string &word, int frequency)
    : _word(word)
    , _frequency(frequency)
    {

    }
	string _word;
	int _frequency;
};

class Dictionary
{
public:
    void read(const string &filename)
    {
        ifstream ifs(filename);
        if(!ifs)
        {
            cerr << "ifstream is not good" << endl;
            return;
        }

        string line;
        while(getline(ifs, line))
        {
            istringstream iss(line);
            string word;
            while(iss >> word)
            {
                //如果单词不合法abc123 abc??
                string newWord = dealWord(word);
                //newWord就是合法的单词，需要将其存放到vector
                insert(newWord);
            }
        }

        ifs.close();
    }

    void store(const string &filename)
    {
        ofstream ofs(filename);
        if(!ofs)
        {
            cerr << "ofstream is not good" << endl;
            return;
        }

        for(size_t idx = 0; idx != _dict.size(); ++idx)
        {
            ofs << _dict[idx]._word 
                << "        " 
                << _dict[idx]._frequency 
                << endl;
        }

        ofs.close();
    }

    string dealWord(const string &word)
    {
        for(size_t idx = 0; idx != word.size(); ++idx)
        {
            /* if(word[idx] >= 'a' && word[idx] <= 'z') */
            /* if(word[idx] >= 'A' && word[idx] <= 'Z') */
            //abc123 hello
            ////判断字符串中的每个字符是不是一个字母
            if(!isalpha(word[idx]))
            {
                return string();
            }
        }

        return word;
    }

    void insert(const string &word)
    {
        if(word == string())
        {
            return;
        }

        //只有是正常的字符串才能将其插入到vector存起来
        size_t idx = 0;
        for(idx = 0; idx != _dict.size(); ++idx)
        {
            //如果单词已经存在vector，就只需要更新频率
            if(word == _dict[idx]._word)
            {
                ++_dict[idx]._frequency;
                break;
            }
        }
        //如果for循环都已经走完了，还没有走到for中if语句
        //那就表明该单词是第一次出现
        if(idx == _dict.size())
        {
            _dict.push_back(Record(word, 1));
        }
    }
private:
	vector<Record> _dict;
};

int main(int argc, char *argv[])
{
    Dictionary dictionary;
    cout << "begin read..." << endl;
    dictionary.read("The_Holy_Bible.txt");
    cout << "finish read..." << endl;
    dictionary.store("wd.data");
    return 0;
}

